<template>
	<view class="addService_box">
		<scroll-view scroll-y class="service_list">
			<view class="service_item_box" v-for="(item, index) in selectedServiceList" :key="index">
				<view class="service_title">
					<view class="title_content">
						<image class="service_picture" :src="item.thumPic"></image>
						<view class="service_name">{{ item.name }}</view>
					</view>
					<view class="service_delete" v-show="selectedServiceList.length > 1" @tap="deleteService(item, index)">删除服务</view>
				</view>
				<view class="service_content">
					<view class="fee_box" v-if="type == 'modify' && item.skuList && item.skuList.length > 0">
						<view class="fee_title">
							<view class="fee_name">请选择服务规格</view>
						</view>
						<view class="service_time_box">
							<view :class="['service_time_item', {'service_time_item_pick': skuItem.selected}]" v-for="skuItem in item.skuList" :key="skuItem.id" @tap.stop="selectServiceTime(item,skuItem)">{{skuItem.serviceTime}}</view>
						</view>
					</view>
					<view class="fee_box">
						<view class="fee_title">
							<view class="fee_name">基础费用设置</view>
							<view class="fee_tips">基础公里范围内、基础宠物数量，对应的的不同服务时长单次费用。</view>
						</view>
						<view class="table_box">
							<view class="table_tr">
								<view class="table_tb">基础公里</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_box">
											<input
												v-model="formBox[index].basicPosition"
												type="number"
												class="item_input"
												placeholder="公里数"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
											<view>KM</view>
										</view>
										<view class="item_input_unit">内</view>
									</view>
								</view>
							</view>
							<view class="table_tr">
								<view class="table_tb">基础宠物</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_box">
											<input
												v-model="formBox[index].basicPetNumber"
												type="number"
												class="item_input"
												placeholder="宠物数量"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
											<view>只</view>
										</view>
										<view class="item_input_unit">内</view>
									</view>
								</view>
							</view>
							<view class="table_tr" v-for="(skuItem, skuIndex) in filterSkuOfService(item.skuList)" :key="skuItem.id">
								<view class="table_tb">{{ skuItem.serviceTime }}/次</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_box">
											<input
												v-model="skuItem.price"
												type="digit"
												class="item_input"
												placeholder="价格"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
										</view>
										<view class="item_input_unit">元</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<view class="fee_box">
						<view class="fee_title">
							<view class="fee_name">加价费用设置</view>
							<view class="fee_tips">超出后每多出的公里加收的费用，以及超出后每增加的宠物加收的费用。</view>
						</view>
						<view class="table_box">
							<view class="table_tr table_th">
								<view class="table_tb"></view>
								<view class="table_tb">公里(KM)</view>
								<view class="table_tb">价格(元)</view>
							</view>
							<view class="table_tr">
								<view class="table_tb">远距离加价</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_unit">每多</view>
										<view class="item_input_box">
											<input
												v-model="formBox[index].extraDistance.distance"
												type="number"
												class="item_input"
												placeholder="公里数"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
										</view>
									</view>
								</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_unit">加价</view>
										<view class="item_input_box">
											<input
												v-model="formBox[index].extraDistance.price"
												type="digit"
												class="item_input"
												placeholder="价格"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="table_box">
							<view class="table_tr table_th">
								<view class="table_tb"></view>
								<view class="table_tb">超出宠物数量(只)</view>
								<view class="table_tb">价格(元)</view>
							</view>
							<view class="table_tr">
								<view class="table_tb">多宠加价</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_unit">每多</view>
										<view class="item_input_box">
											<input
												v-model="formBox[index].extraPets.number"
												type="number"
												class="item_input"
												placeholder="数量"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
										</view>
									</view>
								</view>
								<view class="table_tb">
									<view class="item_input_item">
										<view class="item_input_unit">加价</view>
										<view class="item_input_box">
											<input
												v-model="formBox[index].extraPets.price"
												type="digit"
												class="item_input"
												placeholder="价格"
												placeholder-style="color: #CACCCC;font-size: 26rpx"
											/>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="footer_box">
			<view v-show="type == 'add' && studioId" class="footer_button button_white" @tap="toBack">上一步</view>
			<view class="footer_button button_red" @tap="submitModification">确定并上架</view>
		</view>
	</view>
</template>

<script setup>
import api from '@/api';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { useServiceStore } from '@/store/useServiceStore';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';
import { useStudioGoodsStoreToRefs } from '@/store/useStudioGoodsStore';

// add 添加服务，modify 修改服务
const type = ref('add');
const formBox = ref([]);
const { selectedServiceList } = storeToRefs(useServiceStore());
const { serviceList } = useStudioGoodsStoreToRefs();
const studio = ref({});
const studioId = ref()
const status = ref()
onLoad((data) => {
	status.value = data.status
	studioId.value = data.studioId
	type.value = data.type || type.value;
	submitModification = preventRepeat(submitModification)
	getStudioInfo()
	initFormBox();
	if (type.value == 'modify') {
		getSkuList();
	}
});
onShow(() => {
	console.log('selectedServiceList', selectedServiceList);
});

const filterSkuOfService = (skuList) => {
	if (!(skuList instanceof Array)) return []
	return skuList.filter(item => item.selected)
}

const getStudioInfo = async () => {
	try {
		const res = await api({
			method: 'get',
			url: `/mall/studio/getStudioDetail/${studioId.value}`,
		})
		studio.value = res.data || {}
	} catch (error) {
		studio.value = {}
	}
}

const initFormBox = () => {
	formBox.value = selectedServiceList.value.map((item) => {
		const box = {};
		let petRangeMarkUp = {};
		let petNumMarkUp = {};
		try {
			petRangeMarkUp = JSON.parse(item.petRangeMarkUp);
			petNumMarkUp = JSON.parse(item.petNumMarkUp);
		} catch (err) {
			console.log('err', err);
		}
		box.basicPosition = petRangeMarkUp.startValue || ''; // 基础里程
		box.basicPetNumber = petNumMarkUp.startValue || ''; // 基础宠物数量
		box.extraDistance = {
			// 额外里程
			distance: petRangeMarkUp.outValue || '',
			price: petRangeMarkUp.upPrice || ''
		};
		box.extraPets = {
			// 额外宠物
			number: petNumMarkUp.outValue || '',
			price: petNumMarkUp.upPrice || ''
		};
		box.name = item.name;
		console.log('box', box);
		return box;
	});

	// 修改服务时初始化数据
	if (type.value == 'modify') {
		selectedServiceList.value.forEach((item) => {
			item.skuList.forEach((skuItem) => {
				skuItem.selected = true;
			});
		});
	}
};
const deleteService = (data, index) => {
	selectedServiceList.value.splice(index, 1);
};
const selectServiceTime = (item,skuItem) => {
	skuItem.selected = !skuItem.selected;
};
const validateFormInfoIsEmpty = () => {
	let msg = '';
	formBox.value.some((item) => {
		if (!item.basicPosition) {
			msg = `请填写基础里程`;
		} else if (item.basicPosition > 999) {
			msg = `里程数不得超过999`;
		} else if (item.basicPosition < 1) {
			msg = `里程数不得低于1`;
		} else if (!item.basicPetNumber) {
			msg = `请填写基础宠物数量`;
		}  else if (item.basicPetNumber && item.basicPetNumber > 999) {
			msg = `宠物数量不得超过999`;
		} else if (item.basicPetNumber && item.basicPetNumber < 1) {
			msg = `宠物数量得低于1`;
		} else if (!item.extraDistance.distance) {
			msg = `请填写额外里程数量`;
		} else if (item.extraDistance.distance && item.extraDistance.distance > 999) {
			msg = `里程数不得超过999`;
		} else if (item.extraDistance.distance && item.extraDistance.distance < 1) {
			msg = `里程数不得低于1`;
		}else if (!item.extraDistance.price) {
			msg = `请填写额外里程金额`;
		} else if (!item.extraPets.number) {
			msg = `请填写额外宠物数量`;
		} else if (item.extraPets.number && item.extraPets.number > 999) {
			msg = `宠物数量不得超过999`;
		} else if (item.extraPets.number && item.extraPets.number < 1) {
			msg = `宠物数量得低于1`;
		} else if (!item.extraPets.price) {
			msg = `请填写额外宠物金额`;
		} else if ((item.extraDistance.price && item.extraDistance.price > 99999.99) || (item.extraPets.price && item.extraPets.price > 99999.99)) {
			msg = `价格不得超过99999.99`;
		} else if ((item.extraDistance.price && item.extraDistance.price < 0.01) || (item.extraPets.price && item.extraPets.price < 0.01)) {
			msg = `价格不得低于0.01`;
		} else if ((item.extraDistance.price && !Number(item.extraDistance.price)) || (item.extraPets.price && !Number(item.extraPets.price))) {
			msg = `请输入有效数字`;
		}
		const priceList = [item.extraDistance.price, item.extraPets.price]
		const validateFractionPart = priceList.some(priceItem => {
			return validateFractionLength(priceItem, 2)
		})
		if (validateFractionPart) {
			msg = `价格不能超过两位小数`;
		}
		return msg;
	});
	const isSelected = selectedServiceList.value.some(item => {
		const result = item.skuList.some((skuItem) => {
			return skuItem.selected
		})
		return result
	})
	if (isSelected) {
		selectedServiceList.value.some((item) => {
			const result = item.skuList.some((skuItem) => {
				if (!skuItem.selected) return false
				if (!skuItem.price) {
					msg = `请填写基础费`;
				} else if (!Number(skuItem.price)) {
					msg = `请输入有效数字`;
				} else if (skuItem.price > 99999.99) {
					msg = `价格不得超过99999.99`;
				} else if (skuItem.price < 0.01) {
					msg = `价格不得低于0.01`;
				} else if (validateFractionLength(skuItem.price, 2)) {
					msg = `价格不能超过两位小数`;
				}
				if (msg) return true;
			});
			return result;
		});
	} else {
		msg = `请选择服务时长`;
	}
	
	if (!msg) return false;
	uni.showToast({
		icon: 'none',
		title: msg
	});
	return true;
};
const validateFractionLength = (num, length = 2) => {
	const fractionArr = String(num).split('.') || []
	const fractionPart = fractionArr[1] || ''
	return fractionPart.length > length
}
let submitModification = async () => {
	if (validateFormInfoIsEmpty()) return;
	const params = selectedServiceList.value.map((item, index) => {
		const paramItem = {
			id: item.id,
			goodsId: item.id,
			userId: studio.value.userId,
			studioId: studioId.value,
			description: item.description,
			name: item.name
		};
		paramItem.goodsSkus = item.skuList.filter((skuItem) => {
			skuItem.goodsSkuId = skuItem.id;
			skuItem.studioGoodsId = item.id;
			return skuItem.selected;
		});
		const petRangeMarkUp = {
			startValue: formBox.value[index].basicPosition,
			outValue: formBox.value[index].extraDistance.distance,
			upPrice: formBox.value[index].extraDistance.price
		};
		const petNumMarkUp = {
			startValue: formBox.value[index].basicPetNumber,
			outValue: formBox.value[index].extraPets.number,
			upPrice: formBox.value[index].extraPets.price
		};
		paramItem.petRangeMarkUp = JSON.stringify(petRangeMarkUp);
		paramItem.petNumMarkUp = JSON.stringify(petNumMarkUp);
		return paramItem;
	});
	if (!studioId.value) {
		serviceList.value = params;
	} else {
		if (type.value == 'add') {
			const res = await api({
				method: 'post',
				url: '/mall/studio/studioAddService',
				data: {
					studioGoods: params
				}
			});
		} else {
			const res = await api({
				method: 'put',
				url: '/mall/studio/studioSaveService',
				data: {
					...params[0],
					status:status.value
				}
			});
			// toBack()
		}
		uni.redirectTo({
			url: `/pages/workshopManagement/succeeded/index?studioId=${studioId.value}`
		})
		return
	}
	uni.navigateBack({
		delta: 2
	});
	
	useServiceStore().selectedServiceList = [];
	return
};

const getSkuList = async () => {
	const { data = [] } = await api({
		method: 'get',
		url: '/mall/goods/goods-sku/getGoodsSku',
		data: {
			goodsId: selectedServiceList.value[0].id
		}
	});
	data.forEach((item) => {
		const result = selectedServiceList.value[0].skuList.findIndex((skuItem) => {
			return item.serviceTime == skuItem.serviceTime;
		});
		if (result == -1) {
			selectedServiceList.value[0].skuList.push(item);
		}
	});
	selectedServiceList.value[0].skuList = selectedServiceList.value[0].skuList.sort((a, b) => {
		return a.serviceTime - b.serviceTime;
	})
};

// 防止异步函数执行过程中，重复执行
// 传入的函数必须是promise或者是async函数并决策，
const preventRepeat = (fn) => {
	let isDoing = false;
	return async function () {
		if (isDoing) return;
		isDoing = true;
		// try catch 防止promise抛出错误
		try {
			// 防止this劫持
			await fn.apply(this, arguments);
		} catch (e) {
		} finally {
			// 加定时器是因为接口请求完后到弹窗遮罩出来之前，有一瞬间可以触发点击事件
			setTimeout(() => {
				isDoing = false;
			}, 1000)
		}
	};
};

const toBack = () => {
	uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.addService_box {
	width: 100%;
	height: 100%;
	background: #f9f6f6;
	padding: 24rpx 32rpx;
	padding-bottom: 112rpx;
	padding-bottom: calc(112rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(112rpx + env(safe-area-inset-bottom));
	box-sizing: border-box;

	.service_list {
		height: 100%;

		.service_item_box {
			padding: 32rpx;
			background: #ffffff;
			border-radius: 24rpx;
			margin-bottom: 32rpx;

			.service_title {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title_content {
					flex: 1;
					display: flex;
					align-items: center;

					.service_picture {
						width: 96rpx;
						height: 96rpx;
						border-radius: 24rpx;
						margin-right: 16rpx;
					}
					.service_name {
						font-weight: bold;
						font-size: 36rpx;
						color: #1b2120;
					}
				}
				.service_delete {
					font-size: 26rpx;
					color: #1a1a1a;
					text-decoration-line: underline;
				}
			}

			.service_content {
				
				.fee_title {
					margin-top: 64rpx;
					margin-bottom: 40rpx;
					
					.fee_name {
						font-weight: bold;
						font-size: 32rpx;
						color: #1A1A1A;
					}
					.fee_tips {
						margin-top: 16rpx;
						font-size: 24rpx;
						color: #7C807F;
					}
				}
				
				.item_input_item {
					display: flex;
					align-items: center;
									
					.item_input_unit {
						font-size: 26rpx;
						color: #6363FF;
						margin-right: 4rpx;
					}
					.item_input_box + .item_input_unit{
						margin-right: 0;
						margin-left: 4rpx;
					}
				}
				.item_input_box {
					flex: 1;
					max-width: 360rpx;
					display: flex;
					align-items: center;
					padding: 18rpx 30rpx;
					background-color: #F9F6F6;
					border-radius: 16rpx;
					font-size: 26rpx;
					color: #1B2120;
					font-weight: normal;
					
					.item_input {
						font-size: 30rpx;
						color: #1B2120;
						margin-right: 8rpx;
					}
				}
				
				.service_time_box {
					display: grid;
					grid-template-columns: repeat(3,1fr);
					grid-column-gap: 16rpx;
					grid-row-gap: 24rpx;
					
					.service_time_item {
						height: 70rpx;
						border-radius: 8rpx;
						border: 1rpx solid #CACCCC;
						font-size: 30rpx;
						color: #5C5E5E;
						line-height: 70rpx;
						text-align: center;
					}
					.service_time_item_pick {
						border: 1rpx solid #FF6084;
						color: #FF6084;
					}
				}
				
				.table_box {
					margin-bottom: 24rpx;
					
					.table_tr {
						display: flex;
						border-top: 1rpx solid #E4E6E6;
						
						.table_tb {
							font-weight: bold;
							font-size: 28rpx;
							color: #1B2120;
							padding: 16rpx 14rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							flex: 2;
							border-left: 1rpx solid #E4E6E6;
							box-sizing: border-box;
							text-align: center;
						}
						.table_tb:first-child {
							// flex: 1;
							flex: none;
							width: 164rpx;
							font-weight: normal;
							font-size: 24rpx;
							color: #5C5E5E;
							padding: 16rpx 0;
						}
						.table_tb:last-child {
							flex: 4;
							border-right: 1rpx solid #E4E6E6;
						}
						.table_tb:nth-child(3) {
							flex: 2;
							border-right: 1rpx solid #E4E6E6;
						}
					}
					.table_tr:last-child {
						border-bottom: 1rpx solid #E4E6E6;
					}
					.table_th {
						.table_tb {
							padding: 16rpx 0;
							font-size: 24rpx;
							color: #5C5E5E;
							box-sizing: border-box;
							text-align: center;
						}
					}
				}
			}
		}
	}

	.footer_box {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		background: #ffffff;
		border-top: 1rpx solid #e4e6e6;
		padding: 8rpx 44rpx;
		padding-bottom: calc(8rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(8rpx + env(safe-area-inset-bottom));
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 2;

		.footer_button {
			flex: 1;
			margin-right: 8rpx;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			border: 2rpx solid #ff6084;
			box-sizing: border-box;
			font-size: 28rpx;
			border-radius: 44rpx;
		}
		.button_red {
			color: #ffffff;
			background: linear-gradient( 90deg, #FF6188 0%, #FF5252 100%);
		}
		.button_white {
			color: #ff6084;
			background-color: #ffffff;
		}
		.footer_button:last-child {
			margin-right: 0;
		}
	}
}
</style>
